<template>
  <page-layout>
    <a-row :gutter="[10, 10]">
      <!-- 顶部区域 -->
      <a-col :span="24">
        <a-card>
          <!-- 查询参数 -->
          <go2-query v-if="false"  :searchParam="searchParam" @on-search="search"></go2-query>
        </a-card>
      </a-col>
      <!-- 中心区域 -->
      <a-col :span="24">
        <a-card>
          <!-- 列表 -->
          <go2-table
            ref="tableRef"
            rowKey="id"
            :fetch="fetch"
            :columns="columns"
            :toolbar="toolbar"
            :operate="operate"
            :param="state.param"
            :pagination="pagination"
            :row-selection="{
              selectedRowKeys: state.selectedRowKeys,
              onChange: onSelectChange,
            }"
          >
            <!-- 继承至 a-table 的默认插槽 -->
          </go2-table>
        </a-card>
      </a-col>
    </a-row>
    <add :visible="state.visibleAdd" @close="closeAdd"></add>
    <edit
      :visible="state.visibleEdit"
      @close="closeEdit"
      :record="state.recordEdit"
    ></edit>
    <info
      :visible="state.visibleInfo"
      @close="closeInfo"
      :record="state.recordInfo"
    ></info>
    <addRole
      v-if="state.visibleaddRole"
      :visible="state.visibleaddRole"
      @close="closeaddRole"
      :record="state.recordaddRole"
    ></addRole>
    <addPermission
      v-if="state.visibleaddPermission"
      :visible="state.visibleaddPermission"
      @close="closeaddPermission"
      :record="state.recordaddPermission"
    ></addPermission>
  </page-layout>
</template>

<script>
import { useI18n } from "vue-i18n";
import add from "./modal/add.vue";
import edit from "./modal/edit.vue";
import info from "./modal/info.vue";
import addRole from "./modal/addRole.vue";
import addPermission from "./modal/addPermission.vue";
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { list, remove } from "@/core/api/module/user";
import {
  reactive,
  createVNode,
  ref,
  toRaw,
  onMounted,
  computed,
  watch,
} from "vue";
import { useStore } from "vuex";

const removeKey = "remove";
const removeBatchKey = "removeBatch";

export default {
  components: {
    add,
    edit,
    info,
    addRole,
    addPermission,
  },
  setup() {
    const { t } = useI18n();
    const tableRef = ref();
    const { getters } = useStore();

    const switchFormat = {
      yes: 1,
      no: 0,
      event: function (value, record) {
        return value;
      },
    };

    /// 删除配置
    const removeMethod = (record) => {
       removeIds([record.id])
    }

    //批量删除
    const batchremoveMethod = () => { 
      const romovekeys =  toRaw(state.selectedRowKeys) ;
      if (romovekeys.length<=0) {
        message.error({content:t('please chose'), key: removeBatchKey, duration: 1})
        return false;
      }
       removeIds(romovekeys)
    }

    const removeIds = (Ids) => {
      Modal.confirm({
        title: t('confirm')+t('delete') +'?',
        icon: createVNode(ExclamationCircleOutlined),
        okText: t('ok'),
        cancelText: t('cancel'),
        onOk() {
          message.loading({ content: t('loading'), key: removeKey }); 
          remove({"ids":Ids}).then((response) => {
            if(response.code==0){
              message.success({content: t('Delete succeeded!'), key: removeKey, duration: 1}).then(()=> {
                tableRef.value.reload()
              })
            }else{
              message.error({content:response.msg, key: removeKey, duration: 1})
            }
          })
        }
      });
    }

    const converFormat = [
      { label: "online", value: "online", tag: { color: "green" } },
      { label: "offline", value: "offline", tag: { color: "red" } },
    ];

    /// 列配置
    const columns = [
      { dataIndex: "login_name", key: "login_name" },
      { dataIndex: "user_name", key: "user_name" },
      { dataIndex: "status", key: "status", switch: switchFormat },
      { dataIndex: "isonline", key: "isonline", conver: converFormat },
      {
        dataIndex: "create_time",
        key: "create_time",
        format: { type: "date", value: "YYYY-MM-DD HH:mm:ss" },
      },
      {
        dataIndex: "update_time",
        key: "update_time",
        format: { type: "date", value: "YYYY-MM-DD HH:mm:ss" },
      },
    ];

    /// 数据来源

    //监听在线
    const onlineUser = computed(() => getters.onlineUser); //获取在线用户

    watch(onlineUser, () => {
      stateCache.readCache = true;
      tableRef.value.reload();
    });

    const stateCache = reactive({
      data: [],
      readCache: false,
    });

    const fetch = async (param) => {
      let response = {};
      if (stateCache.readCache) {
        response = stateCache.data;
      } else {
        response = await list(param);
        stateCache.data = response;
      }
      stateCache.readCache = false;

      if (response.code == 0) {
        response.data.list.forEach((item, index) => {
          if (onlineUser.value.indexOf(item.id) > -1) {
            response.data.list[index].isonline = "online";
          } else {
            response.data.list[index].isonline = "offline";
          }
        });
      } else {
        message.error({ content: response.msg, duration: 1 }).then(() => {});
      }

      return {
        data: response.data,
      };
    };

    /// 工具栏
    const toolbar = [
      {
        label: "add",
        code: "/user/add",
        event: function () {
          state.visibleAdd = true;
        },
      },
      {
        label: "batchRemove",
        code: "/user/remove",
        event: batchremoveMethod,
      },
    ];

    /// 行操作
    const operate = [
      {
        label: "info",
        code: false,
        event: function (record) {
          (state.visibleInfo = true), (state.recordInfo = record);
        },
      },
      {
        label: "edit",
        code: "/user/edit",
        event: function (record) {
          (state.visibleEdit = true), (state.recordEdit = record);
        },
      },
      {
        label: "set roles",
        code: "/user/setroles",
        event: function (record) {
          (state.visibleaddRole = true), (state.recordaddRole = record);
        },
      },
      {
        label: "set permissions",
        code: "/user/setpermissions",
        event: function (record) {
          (state.visibleaddPermission = true),
            (state.recordaddPermission = record);
        },
      },
      {
        label: "remove",
        code: "/user/remove",
        event: function (record) {
          removeMethod(record);
        },
      },
    ];

    /// 分页参数
    //const pagination = false;
    /// 分页参数
    const pagination = reactive({
      pageSize: 20,
      page: 1,
    });

    /// 外置参数 - 当参数改变时, 重新触发 fetch 函数
    const state = reactive({
      selectedRowKeys: [],
      param: {},
      visibleAdd: false,
      visibleEdit: false,
      visibleInfo: false,
      visibleaddRole: false,
      visibleaddPermission: false,
      recordEdit: {},
      recordInfo: {},
      recordaddRole: {},
      recordaddPermission: {},
    });

    /// 查询参数
    const searchParam = [
      { key: "user_name", type: "input", label: "user_name" },
      {
        key: "status",
        type: "select",
        label: "status",
        value: 0,
        hidden: true,
        options: [
          { text: "all", value: 0 },
          { text: "open", value: 1 },
          { text: "close", value: 2 },
        ],
      },
    ];

    /// 查询操作
    const search = function (value) {
      state.param = value;
    };

    const onSelectChange = (selectedRowKeys) => {
      state.selectedRowKeys = selectedRowKeys;
    };

    const closeAdd = function (e) {
      state.visibleAdd = false;
      if (e) {
        tableRef.value.reload();
      }
    };

    const closeEdit = function (e) {
      state.visibleEdit = false;
      if (e) {
        tableRef.value.reload();
      }
    };

    const closeInfo = function (e) {
      state.visibleInfo = false;
      if (e) {
        tableRef.value.reload();
      }
    };

    const closeaddRole = function (e) {
      state.visibleaddRole = false;
      if (e) {
        tableRef.value.reload();
      }
    };

    const closeaddPermission = function (e) {
      state.visibleaddPermission = false;
      if (e) {
        tableRef.value.reload();
      }
    };
    return {
      t,
      state,
      fetch,
      search,
      toolbar,
      columns,
      operate,
      pagination,
      searchParam,
      onSelectChange,

      closeAdd,
      closeEdit,
      closeInfo,
      closeaddRole,
      closeaddPermission,

      tableRef,
    };
  },
};
</script>